import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import auth from '../util/auth'

Vue.use(VueRouter)

/**
 * 路由独享守卫
 * @param to
 * @param from
 * @param next
 */
function requireAuth(to,from,next){
  if(!auth.loggedIn()){
    next({
      path:'/login',
      query:{redirect:to.fullPath}
    });
  }else {
    next();
  }
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: ()=>import('../views/Dashboard.vue'),
    beforeEnter:requireAuth
  },
  {
    path: '/login',
    name: 'Login',
    component: ()=>import('../views/Login')
  },
  {
    path: '/logout',
    beforeEnter(to,from,next){
      auth.logout()
      next('/login');
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router
